package leetcode.code0388;

import java.util.Stack;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int lengthLongestPath(String input) {
		char[] cs = input.toCharArray();
		int p = 0;
		int len = cs.length;
		int max = 0, cnt = 0, lastCnt = 0, curTab = 0;
		Stack<int[]> stack = new Stack<>();
		boolean nextDot = false, curDot = false, n = false;
		while (p <= len) {
			// "a \n\t b.txt \n a2\n\tb2.txt"
			char cur = p == len ? 1 : cs[p];
			if (p == len || cur == '\n') {
				if (nextDot) {
					while (!stack.isEmpty() && stack.peek()[1] >= curTab) {
						stack.pop();
					}
					int size = stack.isEmpty() ? 0 : stack.peek()[0] + 1;
					max = Math.max(max, size + cnt);
				}
				lastCnt = cnt;
				curDot = nextDot;
				cnt = 0;
				nextDot = false;
				n = true;
				p++;
			} else if (cur == '\t') {
				int nextTab = 0;
				while (p < len && cs[p] == '\t') {
					p += 1;
					nextTab++;
				}
				if (!curDot) {
					while (!stack.isEmpty() && stack.peek()[1] >= curTab) {
						stack.pop();
					}
					int size = stack.isEmpty() ? 0 : stack.peek()[0] + 1;
					stack.add(new int[] { size + lastCnt, curTab });
				}
				curTab = nextTab;
				if (p == len) {
					break;
				}
				n = false;
			} else {
				cnt++;
				p++;
				if (cur == '.') {
					nextDot = true;
				}
				if (n) {
					n = false;
					curTab = 0;
				}
			}
		}
		return max;
	}

	@Override
	public void debug4() {
		H.compare(10, this.lengthLongestPath("a\n\tb\n\t\tc.txt\n\taaaa.txt"));
		H.compare(14, this.lengthLongestPath("a\n\tb1\n\t\tf1.txt\n\taaaaa\n\t\tf2.txt"));
		H.compare(20, this.lengthLongestPath("dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"));
		H.compare(9, this.lengthLongestPath("a\n\tb.txt\na2\n\tb2.txt"));
		H.compare(20, this.lengthLongestPath("dir\n\t        file.txt\n\tfile2.txt"));
		H.compare(16, this.lengthLongestPath("dir\n        file.txt"));
		H.compare(12, this.lengthLongestPath("file1.txt\nfile2.txt\nlongfile.txt"));
		H.compare(0, this.lengthLongestPath("a"));
//		H.compare(13,
//				this.lengthLongestPath("dir\n\tsubdir1\n \t\tfile 1.ext\n\t\tsubsubdir1\n\t2\n\t\t2\n\t\t\t2.ext"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
		System.out.println("        file.txt".length());
	}

}
